<?php

/*
 * This file is part of Sulu.
 *
 * (c) Sulu GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Route\Application\Routing\Generator;

use Psr\Container\ContainerInterface;
use Sulu\Route\Domain\Exception\MissingRequestContextParameterException;
use Sulu\Route\Domain\Value\RequestAttributeEnum;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Translation\LocaleSwitcher;

final class RouteGenerator implements RouteGeneratorInterface
{
    public function __construct(
        private ContainerInterface $webspaceRouteGeneratorLocator,
        private RequestContext $requestContext,
        private RequestStack $requestStack,
        private LocaleSwitcher $localeSwitcher,
    ) {
    }

    public function generate(string $slug, ?string $locale = null, ?string $webspace = null, int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
    {
        if (null === $webspace) {
            $requestWebspace = $this->requestContext->getParameter(RequestAttributeEnum::WEBSPACE->value);

            if (!\is_string($requestWebspace)) {
                $requestWebspace = $this->requestStack->getCurrentRequest()?->attributes->get(RequestAttributeEnum::WEBSPACE->value);
            }

            if (!\is_string($requestWebspace)) {
                throw new MissingRequestContextParameterException(RequestAttributeEnum::WEBSPACE->value);
            }

            $webspace = $requestWebspace;
        }

        if (null === $locale) {
            $requestLocale = $this->requestContext->getParameter('_locale');
            $locale = $requestLocale;

            if (!\is_string($locale)) {
                $locale = $this->localeSwitcher->getLocale();
            }
        }

        $webspaceRouteGenerator = null;
        if ($this->webspaceRouteGeneratorLocator->has($webspace)) {
            $webspaceRouteGenerator = $this->webspaceRouteGeneratorLocator->get($webspace);
        } elseif ($this->webspaceRouteGeneratorLocator->has('.default')) { // TODO discuss how we should handle this, currently a workaround to avoid register one per webspace
            $webspaceRouteGenerator = $this->webspaceRouteGeneratorLocator->get('.default');
        }

        \assert($webspaceRouteGenerator instanceof WebspaceRouteGeneratorInterface, 'The WebspaceRouteGenerator for "' . $webspace . '" must implement WebspaceRouteGeneratorInterface but got: ' . \get_debug_type($webspaceRouteGenerator));

        $generatedUrl = $webspaceRouteGenerator->generate($this->requestContext, $slug, $locale);

        $schemeAndHttpHost = \sprintf(
            '%s://%s%s/',
            $this->requestContext->getScheme(),
            $this->requestContext->getHost(),
            match ($this->requestContext->getScheme()) {
                'http' => 80 !== $this->requestContext->getHttpPort() ? ':' . $this->requestContext->getHttpPort() : '',
                'https' => 443 !== $this->requestContext->getHttpsPort() ? ':' . $this->requestContext->getHttpsPort() : '',
                default => throw new \RuntimeException('Invalid scheme: ' . $this->requestContext->getScheme()),
            },
        );

        return match (true) {
            UrlGeneratorInterface::NETWORK_PATH === $referenceType && \str_starts_with($generatedUrl, $this->requestContext->getScheme() . '://') => \substr($generatedUrl, \strlen($this->requestContext->getScheme()) + 1),
            UrlGeneratorInterface::ABSOLUTE_PATH === $referenceType && \str_starts_with($generatedUrl, $schemeAndHttpHost) => \substr($generatedUrl, \strlen($schemeAndHttpHost) - 1),
            UrlGeneratorInterface::RELATIVE_PATH === $referenceType && \str_starts_with($generatedUrl, $schemeAndHttpHost) => UrlGenerator::getRelativePath($this->requestContext->getPathInfo(), \substr($generatedUrl, \strlen($schemeAndHttpHost) - 1)),
            default => $generatedUrl,
        };
    }
}
